/*
 *  matlabIO.h
 *  Preview3D
 *
 *  Created by Daniele Panozzo on 2/16/11.
 *  Copyright 2011 DISI - University of Genova. All rights reserved.
 *
 */

#ifndef MATLABIO_H
#define MATLABIO_H

#include <iostream>
/*
 For the file format description see meshplot.m
 */
   
#include <vector>
#include <mat.h>

using namespace std;

class MatlabIO
{
public:
	
	typedef vector<vector<double> > vvd;
	typedef vector<vector<size_t> > vvi;
	
	vvd V; // Point coordinates
	vvi F; // Face indices
	vvd VC; // Vertex Colors
	vvd FC; // Face Colors
	
	MatlabIO()
	{
		error = true;
	}
	
	MatlabIO(const char* file)
	{
		error = read(file);
	}
	
	
	int read(const char* file)
	{
		/*
		 * Open file 
		 */
		MATFile* pmat = matOpen(file, "r");
		if (pmat == NULL) {
			printf("Error reopening file %s\n", file);
			return true;
		}
		
		/*
		 * Read the structures that contains the mesh
		 */
		mxArray* mesh = matGetVariable(pmat, "mesh");
		if (mesh == NULL) {
			printf("Error reading the Mesh structure\n");
			return true;
		}

		// Read vertices positions
		{
			mxArray* mat = mxGetField(mesh, 0, "V");
			if (mat)
			{
				double* ptr = mxGetPr(mat);
				
				int m = mxGetM(mat);
				int n = mxGetN(mat);
				
				V.clear();
				V.resize(m);
				for(int j=0;j<n;j++)
					for(int i=0;i<m;++i)
						V[i].push_back(*(ptr++));
			}
		}

		// Read faces indices
		{
			mxArray* mat = mxGetField(mesh, 0, "F");
			if (mat)
			{
				double* ptr = mxGetPr(mat);
				
				int m = mxGetM(mat);
				int n = mxGetN(mat);
				
				F.clear();
				F.resize(m);
				for(int j=0;j<n;j++)
					for(int i=0;i<m;++i)
						F[i].push_back((size_t)(*(ptr++)-1));
			}
		}
		
		// Read vertices colors
		{
			mxArray* mat = mxGetField(mesh, 0, "VC");
			if (mat)
			{
				cout << "Loading Vertex Colors" << endl;
				double* ptr = mxGetPr(mat);
				
				int m = mxGetM(mat);
				int n = mxGetN(mat);
				
				VC.clear();
				VC.resize(m);
				for(int j=0;j<n;j++)
					for(int i=0;i<m;++i)
						VC[i].push_back(*(ptr++));
			}
		}

		// Read face colors
		{
			mxArray* mat = mxGetField(mesh, 0, "FC");
			if (mat)
			{
				cout << "Loading Face Colors" << endl;

				double* ptr = mxGetPr(mat);
				
				int m = mxGetM(mat);
				int n = mxGetN(mat);
				
				FC.clear();
				FC.resize(m);
				for(int j=0;j<n;j++)
					for(int i=0;i<m;++i)
						FC[i].push_back(*(ptr++));
			}
		}

		/* clean up before exit */
		mxDestroyArray(mesh);
		
		if (matClose(pmat) != 0) {
			printf("Error closing file %s\n",file);
			return true;
		}
		printf("Done\n");
		return false;
	}
	
	bool error;
};

 #endif
